package org.example.wumeng.controller;

import org.example.wumeng.service.T_prescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.example.wumeng.pojo.Prescription;
import org.example.wumeng.pojo.Result;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/prescriptions")
@CrossOrigin(origins = "*", maxAge = 3600)
public class T_prescriptionController {

    @Autowired
    private T_prescriptionService prescriptionService;

    /**
     * 分页查询方剂列表
     */
    @GetMapping
    public Result<List<Prescription>> getList(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "category", required = false) String category,
            @RequestParam(value = "source", required = false) String source) {
        try {
            name = (name != null && !name.trim().isEmpty()) ? name.trim() : null;
            category = (category != null && !category.trim().isEmpty()) ? category.trim() : null;
            source = (source != null && !source.trim().isEmpty()) ? source.trim() : null;

            Map<String, Object> result = prescriptionService.getList(page, size, name, category, source);
            @SuppressWarnings("unchecked")
            List<Prescription> prescriptions = (List<Prescription>) result.get("data");
            Long total = (Long) result.get("total");

            return new Result<>(200, "查询成功", prescriptions, total);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("查询方剂列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取方剂详情
     */
    @GetMapping("/{id}")
    public Result<Prescription> getById(@PathVariable Long id) {
        try {
            Prescription prescription = prescriptionService.getById(id);
            return new Result<>(200, "查询成功", prescription, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.notFound(e.getMessage());
        } catch (Exception e) {
            return Result.error("查询方剂详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建方剂
     */
    @PostMapping
    public Result<Long> create(@RequestBody Prescription prescription) {
        try {
            Long id = prescriptionService.create(prescription);
            return new Result<>(200, "创建成功", id, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("创建方剂失败: " + e.getMessage());
        }
    }

    /**
     * 更新方剂信息
     */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Prescription prescription) {
        try {
            prescriptionService.update(id, prescription);
            return new Result<>(200, "更新成功", null, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新方剂失败: " + e.getMessage());
        }
    }

    /**
     * 删除方剂
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        try {
            prescriptionService.delete(id);
            return new Result<>(200, "删除成功", null, null);

        } catch (IllegalArgumentException e) {
            return Result.badRequest(e.getMessage());
        } catch (RuntimeException e) {
            return Result.badRequest(e.getMessage());
        } catch (Exception e) {
            return Result.error("删除方剂失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类统计方剂数量
     */
    @GetMapping("/count/category")
    public Result<Long> countByCategory(@RequestParam String category) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return Result.badRequest("分类参数不能为空");
            }

            Long count = prescriptionService.countByCategory(category.trim());
            return new Result<>(200, "统计完成", count, null);

        } catch (Exception e) {
            return Result.error("统计方剂数量失败: " + e.getMessage());
        }
    }

    /**
     * 根据出处统计方剂数量
     */
    @GetMapping("/count/source")
    public Result<Long> countBySource(@RequestParam String source) {
        try {
            if (source == null || source.trim().isEmpty()) {
                return Result.badRequest("出处参数不能为空");
            }

            Long count = prescriptionService.countBySource(source.trim());
            return new Result<>(200, "统计完成", count, null);

        } catch (Exception e) {
            return Result.error("统计方剂数量失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类查询方剂
     */
    @GetMapping("/category/{category}")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public Result<List<Prescription>> getByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            if (category == null || category.trim().isEmpty()) {
                return Result.badRequest("分类参数不能为空");
            }
            return prescriptionService.getByCategory(category.trim(), page, size);
        } catch (Exception e) {
            return Result.error("查询分类方剂失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类统计
     */
    @GetMapping("/category/statistics")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public Result<List<Map<String, Object>>> getCategoryStatistics() {
        try {
            return prescriptionService.getCategoryStatistics();
        } catch (Exception e) {
            return Result.error("获取分类统计失败: " + e.getMessage());
        }
    }
}